﻿using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer.Core;
using EPiServer.Editor;
using EPiServer.Framework.DataAnnotations;
using EPiServer.Web;
using EPiServer.Web.PropertyControls;
using EPiServer.Web.Routing;
using OpenWaves.ImageTransformations.Web.Controls;

namespace OpenWaves.EPiServer.ImageProperty
{
    [TemplateDescriptor(TagString = ImageProperty.UIHint)]
    public class PropertyImageControl : PropertyUrlControl, IRenderTemplate<ContentReference>,
                                              IRenderTemplate
    {
        public override void CreateDefaultControls()
        {
            var image = new OpenWaves.ImageTransformations.Web.Controls.Image
            {
                ToolTip = this.ToolTip
            };

            if (this.PropertyData != null && this.PropertyData.Value != null)
            {
                var contentReference = (ContentReference)this.PropertyData.Value;
                var resolver = global::EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<UrlResolver>();
                var url = resolver.GetUrl(contentReference);
                image.ImageUrl = url;
                ServiceLocator.Resolve<IImagePropertiesMapper>().MapProperties(contentReference, image);
            }

            if (!string.IsNullOrWhiteSpace(image.ImageUrl))
            {
                image.Transformation = this.GetImageTransformation();
                image.Width = this.GetIntegerValue("ImageWidth", 200);
                image.Height = this.GetIntegerValue("ImageHeight", 200);

                if (this.RenderSettings.ContainsKey("AlternateText"))
                    image.AlternateText = (string)this.RenderSettings["AlternateText"];
            }

            var imageContainer = new ImageContainerControl(HtmlTextWriterTag.Span);
            imageContainer.Controls.Add(image);

            const string imageWrapperCssClass = "image-wrapper";

            if (PageEditing.PageIsInEditMode)
            {
                var literalControl = new LiteralControl
                {
                    Text =
                        string.Concat("<style type=\"text/css\" rel=\"stylesheet\">.", imageWrapperCssClass, " { display:inline-block; }</style>")
                };
                this.Page.Header.Controls.Add(literalControl);
            }

            this.CopyWebAttributes(imageContainer);

            if (string.IsNullOrWhiteSpace(imageContainer.CssClass))
            {
                imageContainer.CssClass = imageWrapperCssClass;
            }
            else
            {
                imageContainer.CssClass += String.Concat(" ", imageWrapperCssClass);
            }

            this.Controls.Add(imageContainer);
        }

        private ImageTransformationType GetImageTransformation()
        {
            object transformation;
            if (this.RenderSettings.TryGetValue("ImageTransformation", out transformation) && transformation != null)
            {
                ImageTransformationType transformationType;
                if (Enum.TryParse(transformation as string, true, out transformationType))
                {
                    return transformationType;
                }
            }

            return ImageTransformationType.None;
        }

        private int GetIntegerValue(string key, int defaultValue)
        {
            if (!this.RenderSettings.ContainsKey(key))
            {
                return defaultValue;
            }

            int value;
            if (int.TryParse(this.RenderSettings[key] as string, NumberStyles.Integer, CultureInfo.InvariantCulture,
                             out value))
            {
                return value;
            }
            return defaultValue;
        }

        /// <summary>
        /// EPiServer check:
        /// !control.GetType().IsSubclassOf(typeof (WebControl))
        /// we need simple class that inherits from WebControl
        /// </summary>
        private class ImageContainerControl : WebControl
        {
            protected ImageContainerControl()
            {
            }

            public ImageContainerControl(HtmlTextWriterTag tag)
                : base(tag)
            {
            }
        }
    }
}